import React, {
  ReactElement,
  useContext,
  useEffect,
  useMemo,
  useState
} from 'react';
import { View, Text, Image, DeviceEventEmitter, ViewStyle } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import { RtcRemoteView } from 'react-native-agora';

import styles from './style';
import { phonePx } from '../../../../../../util/adapt';
import { classRoomGold } from '../../../../../../constant/resource';
import { Store } from '../../../../reducer';
import { GRADIENT_BLACK_BACKGROUND_COLOR } from '../../../../../../constant/color';
import {
  CLASS_ROOM_RIGHT_SCALE,
  LIVE_HEIGHT,
  LIVE_WIDTH,
  PPTType
} from '../../../../constant';
import Corner from '../../../Graph/Corner';
import GetCoinAnimate from '../../../GetCoinAnimate';
import { CLASS_ROOM_EVENT_SUBMIT_SUCCESS } from '../../../../event';
import { SubmitSuccessData } from '../../../../types';
import { isIOS } from '../../../../../../constant';

interface UserLiveProps {
  userId: string;
  goldCoinNum: number;
  haveAnswer: boolean;
  name: string;
  style?: ViewStyle | ViewStyle[];
  useTextureView?: boolean;
}

export default ({
  userId,
  goldCoinNum,
  name,
  haveAnswer,
  useTextureView = false,
  style
}: UserLiveProps): ReactElement => {
  const [addGoldCoinNum, setAddGoldCoinNum] = useState<number>(0);
  const [hideGoldCoin, setHideGoldCoin] = useState<boolean>(false);

  const { state } = useContext(Store);
  const { isJoinedChannel, channel, showProblemWait, currentPPT } = state;
  const { type } = currentPPT;
  const isProblem = type === PPTType.Problem;

  useEffect((): (() => void) => {
    const subscription = DeviceEventEmitter.addListener(
      CLASS_ROOM_EVENT_SUBMIT_SUCCESS,
      (data: SubmitSuccessData): void => {
        const {
          userId: localUserId,
          addGoldCoinNum: localAddGoldCoinNum
        } = data;
        if (Number(localUserId) === Number(userId)) {
          setAddGoldCoinNum(localAddGoldCoinNum);
        }
      }
    );
    return (): void => {
      if (subscription) {
        subscription.remove();
      }
    };
  }, [userId]);

  return useMemo((): ReactElement => {
    if (!isJoinedChannel) return <View />;

    return (
      <View style={[styles.kid, style]}>
        <View style={styles.loadVideo}>
          {isJoinedChannel && channel && !showProblemWait && !useTextureView ? (
            <RtcRemoteView.SurfaceView
              style={styles.remoteVideo}
              renderMode={1}
              channelId={channel}
              uid={Number(userId)}
              zOrderMediaOverlay
              zOrderOnTop
              key={`${channel}-${userId}`}
            />
          ) : null}
          {isJoinedChannel && channel && !showProblemWait && useTextureView ? (
            <RtcRemoteView.TextureView
              style={styles.remoteVideo}
              renderMode={1}
              channelId={channel}
              uid={Number(userId)}
              key={`${channel}-${userId}`}
            />
          ) : null}
          {isProblem && !haveAnswer && (
            <View style={styles.problem}>
              <Text style={styles.problemDesc}>正在做题</Text>
            </View>
          )}
        </View>
        <LinearGradient
          colors={GRADIENT_BLACK_BACKGROUND_COLOR}
          style={styles.nameContent}
          start={{ x: 0.0, y: 1.0 }}
          end={{ x: 0.0, y: 0.0 }}
        >
          <Text style={styles.name} numberOfLines={1}>
            {name}
          </Text>
          <View style={styles.goldContent}>
            {hideGoldCoin ? (
              <View style={styles.goldIcon} />
            ) : (
              <Image source={classRoomGold} style={styles.goldIcon} />
            )}
            <Text style={styles.goldDesc}>{goldCoinNum}</Text>
          </View>
        </LinearGradient>
        {addGoldCoinNum > 0 && (
          <GetCoinAnimate
            addGoldCoinNum={addGoldCoinNum}
            clearGoldCoinNum={(): void => {
              setAddGoldCoinNum(0);
              setHideGoldCoin(false);
            }}
            x={phonePx(9.5) * CLASS_ROOM_RIGHT_SCALE}
            y={phonePx(18.5) * CLASS_ROOM_RIGHT_SCALE}
            scale={0.55556}
            style={styles.getCoin}
            hideGoldCoinNum={(): void => {
              setHideGoldCoin(true);
            }}
          />
        )}
        <Corner
          style={styles.corner}
          width={LIVE_WIDTH}
          height={LIVE_HEIGHT}
          dia={phonePx(4) * CLASS_ROOM_RIGHT_SCALE}
        />
      </View>
    );
  }, [
    addGoldCoinNum,
    channel,
    goldCoinNum,
    haveAnswer,
    hideGoldCoin,
    isJoinedChannel,
    isProblem,
    name,
    showProblemWait,
    style,
    useTextureView,
    userId
  ]);
};
